const { BASE_URL, SUCCESS_CODE, LOGIN_TIMEOUT_CODE } = require('../config/index.js');
let TOTAL_LOADING = false;
const PENDING_LIST = [];

const http = {
  get(url, data, opt) {
    return this.ajax('GET', url, data, opt);
  },
  post(url, data, opt) {
    return this.ajax('POST', url, data, opt);
  },
  put(url, data, opt) {
    return this.ajax('PUT', url, data, opt);
  },
  delete(url, data, opt) {
    return this.ajax('DELETE', url, data, opt);
  },
  ajax(method, url, data, opt) {
    const loading = opt?.cancelLoading === true ? false : true;
    const timestamp = Date.now() + '';
    PENDING_LIST.push({
      timestamp,
      url,
      data,
      loading,
    });
    return new Promise((resolve, reject) => {
      if (PENDING_LIST.some(v => v.loading)) {
        if (!TOTAL_LOADING) {
          TOTAL_LOADING = true;
          uni.showLoading({
            title: opt?.loadingText || '加载中',
            mask: true,
          });
        };
      };
      uni.request({
        url: `${BASE_URL}${url}`,
        method,
        data,
        header: {
          'type': 'user',
          'Content-Type': opt?.submitType === 'json' ? 'applicaton/json' : 'application/x-www-form-urlencoded',
          'token': uni.getStorageSync('token') || '',
        },
        success(res) {
          PENDING_LIST.map(v => {
            if (v.url === url && v.timestamp === timestamp && v.data === data) {
              v.loading = false
            }
            return v;
          })
          if (PENDING_LIST.every(v => !v.loading)) {
            TOTAL_LOADING = false;
            uni.hideLoading();
          };
          if (res.statusCode !== 200) {
            uni.showToast({
              icon: 'none',
              title: '服务器连接失败',
            });
            reject({ errMsg: '服务器连接失败' });
            return;
          };
          const { code, msg } = res.data;
          if (code === SUCCESS_CODE || code === 30000) {
            // 成功
            resolve(res.data);
          } else if (code === LOGIN_TIMEOUT_CODE) {
            // 登录失效
            uni.showModal({
              title: '提示',
              content: msg,
              showCancel: false,
              confirmText: '我知道了',
              success(res) {
                if (res.confirm) {
                  // 跳转登录页
                  uni.clearStorageSync();
                  uni.reLaunch({
                    url: '/pages/login/login',
                  });
                }
              },
            })
          } else {
            // 错误
            uni.showToast({
              icon: 'none',
              title: msg,
            });
            reject({ errMsg: msg });
          };
        },
        fail(err) {
          PENDING_LIST.map(v => {
            if (v.url === url && v.timestamp === timestamp && v.data === data) {
              v.loading = false
            }
            return v;
          })
          if (PENDING_LIST.every(v => !v.loading)) {
            TOTAL_LOADING = false;
            uni.hideLoading();
          };
          uni.showToast({
            icon: 'none',
            title: err.errMsg,
          });
          reject({ errMsg: err.errMsg });
        },
      });
    });
  }
};

module.exports = http;